package com.hxzy.service.impl;

import com.hxzy.annoation.Log;
import com.hxzy.annoation.MyLog;
import com.hxzy.exceptions.MyException;
import com.hxzy.mapper.DeptMapper;
import com.hxzy.mapper.EmpMapper;
import com.hxzy.pojo.Dept;
import com.hxzy.pojo.DeptLog;
import com.hxzy.service.DeptLogService;
import com.hxzy.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wzm
 * @create 2024-03-04 15:33
 * project_name:JavaWeb2401
 * @Description
 */
@Service
public class DeptServiceImpl implements DeptService {
    //创建mapper对象
    @Autowired
    private DeptMapper deptMapper;
    //注入empMapper
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

//    @MyLog //加上自定义注解
    @Override
    public List<Dept> list() {
        List<Dept> deptList =  deptMapper.getList();
//        int num = 1/0;
        return deptList;
    }

    @Log //添加日志
    @Override
    @Transactional(rollbackFor = Exception.class) //当前方法添加了事务 指定了任何异常都出现问题都回滚
    public void delete(Integer id) throws Exception {
        try {

            //根据id删除部门信息
            deptMapper.delete(id);

            //设置异常 模拟两个操作之间出现了问题
//        int i = 1/0;

            //编译时异常
         /*   if (true) {
                throw new Exception("出现了自己的异常~~");
            }*/

            //同时删除部门下员工的信息
            empMapper.deleteByDeptId(id);
        }finally {
            //无论是否删除成功 都需要记录操作日志到日志表中
            //添加日志到DeptLog表中 调用servcie：service用于添加事务 service可以调用多个操作
            DeptLog deptLog = new DeptLog(null,LocalDateTime.now(),"执行了解散部门的操作，此时解散的部门编号为："+id+"的部门");
            deptLogService.addLog(deptLog);
        }
    }

   /* @MyLog*/
    @Log
    @Override
    public void insert(Dept dept) {
        //补全dept的数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.selectDeptById(id);
    }

    @Log
    @Override
    public void update(Dept dept) {
        //什么时候修改的update_time就是什么时候
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }
}
